/**
 * 校园智能快递集散系统
 * 程序设计基础课程设计(2024级)
 *
 * 本文件包含用户界面模块的实现
 */

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "user_interface_UI.h"
#include "user_management.h"
#include "system_types.h"
#include "fileIO.h"

 // 辅助函数，清除输入缓冲区
static void clearInputBuffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

// 显示常规用户菜单
void showRegularUserMenu(User* currentUser) {
    printf("\n=====================================\n");
    printf("用户菜单-(%s)\n",
        currentUser->type == USER_VIP ? "VIP用户" : "普通用户");
    printf("=====================================\n");
    printf("1. 查看我的包裹信息\n");
    printf("2. 查看我的通知\n");
    printf("3. 查看个人用户信息\n");
    printf("4. 修改个人信息\n");
    printf("5. 注销账户\n");
    printf("6. 开通VIP\n");
    printf("0. 返回主菜单\n");
    printf("当前用户: %s\n", currentUser->username);
    printf("\n请选择: ");
}

// 显示管理员用户菜单
void showAdminUserMenu(User* currentUser) {
    printf("\n=====================================\n");
    printf("管理员用户管理菜单");
    printf("\n=====================================\n");
    printf("1. 查看全部用户信息\n");
    printf("2. 按用户类型查看用户信息\n");
    printf("3. 按手机号查找用户信息\n");
    printf("4. 修改用户信息\n");
    printf("5. 设置用户VIP等级\n");
    printf("6. 设置用户权限\n");
    printf("7. 添加用户权限\n");
    printf("8. 移除用户权限\n");
    printf("9. 注销用户\n");
    printf("0. 返回主菜单\n");
    printf("当前用户: %s\n", currentUser->username);
    printf("\n请选择: ");
}

// 显示快递员用户菜单
void showCourierUserMenu(User* currentUser) {
    printf("\n=====================================\n");
    printf("快递员用户菜单");
    printf("\n=====================================\n");
    printf("1. 包裹入库\n");
    printf("2. 查看我的派送记录\n");
    printf("3. 查看个人用户信息\n");
    printf("4. 修改个人信息\n");
    printf("5. 注销账户\n");
    printf("0. 返回主菜单\n");
    printf("当前用户: %s\n", currentUser->username);
    printf("\n请选择: ");
}

// 显示工作人员用户菜单
void showStaffUserMenu(User* currentUser) {
    printf("\n=====================================\n");
    printf("驿站工作人员菜单");
    printf("\n=====================================\n");
    printf("1. 包裹管理\n");
    printf("2. 货架管理\n");
    printf("3. 用户查询\n");
    printf("4. 查看个人用户信息\n");
    printf("5. 修改个人信息\n");
    printf("6. 注销账户\n");
    printf("0. 返回主菜单\n");
    printf("当前用户: %s\n", currentUser->username);
    printf("\n请选择: ");
}

// 显示用户类型特定的菜单
int showUserTypeSpecificMenu(SystemData* data, User* currentUser) {
    int choice = 0;

    // 根据用户类型显示不同的菜单
    switch (currentUser->type) {
    case USER_ADMIN:
        showAdminUserMenu(currentUser);
        break;

    case USER_STUDENT:
    case USER_VIP:
        showRegularUserMenu(currentUser);
        break;

    case USER_COURIER:
        showCourierUserMenu(currentUser);
        break;

    case USER_STAFF:
        showStaffUserMenu(currentUser);
        break;

    default:
        printf("未知用户类型！\n");
        return -1;
    }
    printf("请选择:\n");
    scanf("%d", &choice);
    clearInputBuffer();

    return choice;
}

// 处理用户信息查看功能
void handleViewUserInfo(SystemData* data, User* currentUser) {
    char* permissionDesc = getUserPermissionDescription(currentUser->permissions);
    printf("\n=====================================\n");
    printf("用户信息");
    printf("\n=====================================\n");
    printf("用户名: %s\n", currentUser->username);
    printf("手机号: %s\n", currentUser->phone);
    printf("地址: %s\n", currentUser->address);
    printf("用户类型: %s\n", getUserTypeString(currentUser->type));
    printf("权限: %s\n", permissionDesc);

    free(permissionDesc);

    printf("\n按Enter键继续...");
    getchar();
}

// 处理用户信息修改功能
void handleUpdateUserInfo(SystemData* data, User* currentUser) {
    char newPassword[MAX_PASSWORD_LEN] = { 0 };
    char newPhone[MAX_PHONE_LEN] = { 0 };
    char newAddress[MAX_ADDRESS_LEN] = { 0 };

    printf("\n=====================================\n");
    printf("修改个人信息");
    printf("\n=====================================\n");
    printf("新密码 (留空表示不修改): ");
    fgets(newPassword, sizeof(newPassword), stdin);
    newPassword[strcspn(newPassword, "\n")] = 0;

    printf("新手机号 (留空表示不修改): ");
    fgets(newPhone, sizeof(newPhone), stdin);
    newPhone[strcspn(newPhone, "\n")] = 0;

    printf("新地址 (留空表示不修改): ");
    fgets(newAddress, sizeof(newAddress), stdin);
    newAddress[strcspn(newAddress, "\n")] = 0;

    ErrorCode result = updateUserInfo(data, currentUser->phone,
        strlen(newPassword) > 0 ? newPassword : NULL,
        strlen(newPhone) > 0 ? newPhone : NULL,
        strlen(newAddress) > 0 ? newAddress : NULL,
        currentUser);

    if (result == OK) {
        printf("\n信息修改成功！\n");
    }
    else {
        printf("\n信息修改失败，错误码: %d\n", result);
        switch (result) {
        case ERR_INVALID_PARAM:
            printf("输入参数无效！\n");
            break;
        case ERR_NO_PERMISSION:
            printf("无权限修改！\n");
            break;
        case ERR_NOT_FOUND:
            printf("未找到该用户！\n");
            break;
        default:
            printf("未知错误！\n");
            break;
        }
    }

    printf("\n按Enter键继续...");
    getchar();
}

// 处理用户注销功能
int handleDeleteUser(SystemData* data, User* currentUser) {
    char confirmation[10];

    printf("\n=====================================\n");
    printf("账户注销");
    printf("\n=====================================\n");
    printf("注意: 此操作将永久删除您的账户，所有数据无法恢复！\n");
    printf("要继续注销，请输入 'confirm': ");
    scanf("%s", confirmation);
    clearInputBuffer();

    if (strcmp(confirmation, "confirm") != 0) {
        printf("\n注销操作已取消！\n");
        printf("\n按Enter键继续...");
        getchar();
        return 0;
    }

    ErrorCode result = deleteUser(data, currentUser->phone, currentUser);

    if (result == OK) {
        printf("\n账户已成功注销！\n");
        printf("\n按Enter键继续...");
        getchar();
        return 1;
    }
    else {
        printf("\n账户注销失败，错误码: %d\n", result);
        switch (result) {
        case ERR_INVALID_PARAM:
            printf("输入参数无效！\n");
            break;
        case ERR_NO_PERMISSION:
            printf("无权限执行此操作！\n");
            break;
        case ERR_NOT_FOUND:
            printf("未找到该用户！\n");
            break;
        default:
            printf("未知错误！\n");
            break;
        }
        printf("\n按Enter键继续...");
        getchar();
        return 0;
    }
}

// 处理管理员特有的用户管理功能
int handleAdminUserManagement(SystemData* data, User* currentUser, int choice) {
    switch (choice) {
    case 1: { // 查看全部用户信息
        int userCount;
        User** users = getAllUsers(data, &userCount, currentUser);

        if (users == NULL || userCount == 0) {
            printf("\n没有找到用户！\n");
        }
        else {
            printf("\n系统共有 %d 个用户:\n", userCount);
            printf("-----------------------------------------------\n");
            printf("%-15s %-10s %-15s %-20s\n", "用户名", "类型", "手机号", "权限");
            printf("-----------------------------------------------\n");

            for (int i = 0; i < userCount; i++) {
                char* permissionDesc = getUserPermissionDescription(users[i]->permissions);
                printf("%-15s %-10s %-15s %-20s\n",
                    users[i]->username,
                    getUserTypeString(users[i]->type),
                    users[i]->phone,
                    permissionDesc);
                free(permissionDesc);
            }

            free(users);
        }
        break;
    }

    case 2: { // 按用户类型查看用户信息
        int typeChoice;
        printf("\n请选择用户类型:\n");
        printf("1. 学生\n");
        printf("2. VIP用户\n");
        printf("3. 快递员\n");
        printf("4. 驿站工作人员\n");
        printf("5. 管理员\n");
        printf("请输入: ");
        scanf("%d", &typeChoice);
        clearInputBuffer();

        if (typeChoice < 1 || typeChoice > 5) {
            printf("\n无效的用户类型！\n");
            break;
        }

        int userCount;
        User** users = getUsersByType(data, (UserType)typeChoice, &userCount, currentUser);

        if (users == NULL || userCount == 0) {
            printf("\n没有找到该类型的用户！\n");
        }
        else {
            printf("\n找到 %d 个 %s 用户:\n", userCount, getUserTypeString((UserType)typeChoice));
            printf("-----------------------------------------------\n");
            printf("%-15s %-15s %-30s\n", "用户名", "手机号", "地址");
            printf("-----------------------------------------------\n");

            for (int i = 0; i < userCount; i++) {
                printf("%-15s %-15s %-30s\n",
                    users[i]->username,
                    users[i]->phone,
                    users[i]->address);
            }

            free(users);
        }
        break;
    }

    case 3: { // 按手机号查找用户信息
        char targetPhone[MAX_PHONE_LEN];
        printf("\n请输入要查找的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);

        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
        }
        else {
            char* permissionDesc = getUserPermissionDescription(targetUser->permissions);
            printf("\n=== 用户信息 ===\n");
            printf("用户名: %s\n", targetUser->username);
            printf("手机号: %s\n", targetUser->phone);
            printf("地址: %s\n", targetUser->address);
            printf("用户类型: %s\n", getUserTypeString(targetUser->type));
            printf("权限: %s\n", permissionDesc);
            free(permissionDesc);
        }
        break;
    }

    case 4: { // 修改用户信息
        char targetPhone[MAX_PHONE_LEN];
        char newPassword[MAX_PASSWORD_LEN] = { 0 };
        char newPhone[MAX_PHONE_LEN] = { 0 };
        char newAddress[MAX_ADDRESS_LEN] = { 0 };

        printf("\n=== 修改用户信息 ===\n");
        printf("请输入要修改的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);
        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
            break;
        }

        printf("\n当前用户信息:\n");
        printf("用户名: %s\n", targetUser->username);
        printf("手机号: %s\n", targetUser->phone);
        printf("地址: %s\n", targetUser->address);
        printf("用户类型: %s\n", getUserTypeString(targetUser->type));

        printf("\n新密码 (留空表示不修改): ");
        fgets(newPassword, sizeof(newPassword), stdin);
        newPassword[strcspn(newPassword, "\n")] = 0;

        printf("新手机号 (留空表示不修改): ");
        fgets(newPhone, sizeof(newPhone), stdin);
        newPhone[strcspn(newPhone, "\n")] = 0;

        printf("新地址 (留空表示不修改): ");
        fgets(newAddress, sizeof(newAddress), stdin);
        newAddress[strcspn(newAddress, "\n")] = 0;

        ErrorCode result = updateUserInfo(data, targetPhone,
            strlen(newPassword) > 0 ? newPassword : NULL,
            strlen(newPhone) > 0 ? newPhone : NULL,
            strlen(newAddress) > 0 ? newAddress : NULL,
            currentUser);

        if (result == OK) {
            printf("\n用户信息修改成功！\n");
        }
        else {
            printf("\n用户信息修改失败，错误码: %d\n", result);
            switch (result) {
            case ERR_INVALID_PARAM:
                printf("输入参数无效！\n");
                break;
            case ERR_NO_PERMISSION:
                printf("无权限修改！\n");
                break;
            case ERR_NOT_FOUND:
                printf("未找到该用户！\n");
                break;
            default:
                printf("未知错误！\n");
                break;
            }
        }
        break;
    }

    case 5: { // 设置用户VIP等级
        char targetPhone[MAX_PHONE_LEN];

        printf("\n=== 设置用户VIP等级 ===\n");
        printf("请输入要设置VIP的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);
        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
            break;
        }

        if (targetUser->type != USER_STUDENT) {
            printf("\n只有普通用户可以设置为VIP！\n");
            break;
        }

        ErrorCode result = setUserVIPLevel(data, targetPhone, currentUser);

        if (result == OK) {
            printf("\n用户已成功设置为VIP！\n");
        }
        else {
            printf("\n设置VIP失败，错误码: %d\n", result);
            switch (result) {
            case ERR_INVALID_PARAM:
                printf("输入参数无效！\n");
                break;
            case ERR_NO_PERMISSION:
                printf("无权限设置！\n");
                break;
            case ERR_NOT_FOUND:
                printf("未找到该用户！\n");
                break;
            default:
                printf("未知错误！\n");
                break;
            }
        }
        break;
    }

    case 6: { // 设置用户权限
        char targetPhone[MAX_PHONE_LEN];
        unsigned int permissions;

        printf("\n=== 设置用户权限 ===\n");
        printf("请输入要设置权限的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);
        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
            break;
        }

        printf("\n当前用户权限: %u\n", targetUser->permissions);
        printf("请输入新的权限位掩码: ");
        scanf("%u", &permissions);
        clearInputBuffer();

        ErrorCode result = setUserPermissions(data, targetPhone, permissions, currentUser);

        if (result == OK) {
            printf("\n用户权限设置成功！\n");
        }
        else {
            printf("\n权限设置失败，错误码: %d\n", result);
            switch (result) {
            case ERR_INVALID_PARAM:
                printf("输入参数无效！\n");
                break;
            case ERR_NO_PERMISSION:
                printf("无权限设置！\n");
                break;
            case ERR_NOT_FOUND:
                printf("未找到该用户！\n");
                break;
            default:
                printf("未知错误！\n");
                break;
            }
        }
        break;
    }

    case 7: { // 添加用户权限
        char targetPhone[MAX_PHONE_LEN];
        unsigned int permission;

        printf("\n=== 添加用户权限 ===\n");
        printf("请输入要添加权限的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);
        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
            break;
        }

        printf("\n当前用户权限: %u\n", targetUser->permissions);
        printf("权限说明:\n");
        printf("1 - 包裹入库\n");
        printf("2 - 包裹出库\n");
        printf("4 - 用户管理\n");
        printf("8 - 货架管理\n");
        printf("16 - 数据统计\n");
        printf("32 - 系统设置\n");
        printf("请输入要添加的权限位掩码: ");
        scanf("%u", &permission);
        clearInputBuffer();

        ErrorCode result = addUserPermission(data, targetPhone, permission, currentUser);

        if (result == OK) {
            printf("\n用户权限添加成功！\n");
        }
        else {
            printf("\n权限添加失败，错误码: %d\n", result);
            switch (result) {
            case ERR_INVALID_PARAM:
                printf("输入参数无效！\n");
                break;
            case ERR_NO_PERMISSION:
                printf("无权限添加！\n");
                break;
            case ERR_NOT_FOUND:
                printf("未找到该用户！\n");
                break;
            default:
                printf("未知错误！\n");
                break;
            }
        }
        break;
    }

    case 8: { // 移除用户权限
        char targetPhone[MAX_PHONE_LEN];
        unsigned int permission;

        printf("\n=== 移除用户权限 ===\n");
        printf("请输入要移除权限的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);
        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
            break;
        }

        printf("\n当前用户权限: %u\n", targetUser->permissions);
        printf("权限说明:\n");
        printf("1 - 包裹入库\n");
        printf("2 - 包裹出库\n");
        printf("4 - 用户管理\n");
        printf("8 - 货架管理\n");
        printf("16 - 数据统计\n");
        printf("32 - 系统设置\n");
        printf("请输入要移除的权限位掩码: ");
        scanf("%u", &permission);
        clearInputBuffer();

        ErrorCode result = removeUserPermission(data, targetPhone, permission, currentUser);

        if (result == OK) {
            printf("\n用户权限移除成功！\n");
        }
        else {
            printf("\n权限移除失败，错误码: %d\n", result);
            switch (result) {
            case ERR_INVALID_PARAM:
                printf("输入参数无效！\n");
                break;
            case ERR_NO_PERMISSION:
                printf("无权限移除！\n");
                break;
            case ERR_NOT_FOUND:
                printf("未找到该用户！\n");
                break;
            default:
                printf("未知错误！\n");
                break;
            }
        }
        break;
    }

    case 9: { // 注销用户
        char targetPhone[MAX_PHONE_LEN];
        char confirmation[10];

        printf("\n=== 注销用户 ===\n");
        printf("请输入要注销的用户手机号: ");
        scanf("%s", targetPhone);
        clearInputBuffer();

        User* targetUser = findUserByPhone(data, targetPhone);
        if (targetUser == NULL) {
            printf("\n未找到该用户！\n");
            break;
        }

        printf("\n确认要注销用户 %s (%s) 吗？此操作不可恢复！\n",
            targetUser->username, targetUser->phone);
        printf("输入 'confirm' 确认: ");
        scanf("%s", confirmation);
        clearInputBuffer();

        if (strcmp(confirmation, "confirm") != 0) {
            printf("\n操作已取消！\n");
            break;
        }

        ErrorCode result = deleteUser(data, targetPhone, currentUser);

        if (result == OK) {
            printf("\n用户注销成功！\n");
        }
        else {
            printf("\n用户注销失败，错误码: %d\n", result);
            switch (result) {
            case ERR_INVALID_PARAM:
                printf("输入参数无效！\n");
                break;
            case ERR_NO_PERMISSION:
                printf("无权限注销！\n");
                break;
            case ERR_NOT_FOUND:
                printf("未找到该用户！\n");
                break;
            default:
                printf("未知错误！\n");
                break;
            }
        }
        break;
    }

    case 0:
        return 0;

    default:
        printf("\n无效的选择！\n");
        break;
    }

    printf("\n按Enter键继续...");
    getchar();
    return 1;
}

// 处理普通用户、快递员、工作人员共享功能
int handleRegularUserFunctions(SystemData* data, User* currentUser, int choice) {
    return 1;
}

// 处理登录的用户的菜单选择
void showUserManagementMenu1(SystemData* data, User* currentUser) {
    if (currentUser == NULL) {
        printf("错误：未登录用户！\n");
        return;
    }

    int running = 1;

    while (running) {
        system("cls"); // 清屏

        int choice = showUserTypeSpecificMenu(data, currentUser);

        if (choice == 0) {
            break; // 返回主菜单
        }

        // 处理管理员特有的功能
        if (currentUser->type == USER_ADMIN) {
            running = handleAdminUserManagement(data, currentUser, choice);
        }
        // 处理其他用户类型共享的功能
        else {
            // 学生和VIP用户菜单前两项是未实现的查看包裹和通知
            if (currentUser->type == USER_STUDENT || currentUser->type == USER_VIP) {
                if (choice == 1) {
                    printf("\n查看我的包裹信息功能需在主菜单->包裹管理中访问\n");
                    printf("\n按Enter键继续...");
                    getchar();
                    continue;
                }
                else if (choice == 2) {
                    printf("\n查看我的通知功能需在主菜单->我的通知中访问\n");
                    printf("\n按Enter键继续...");
                    getchar();
                    continue;
                }
            }

            // 快递员特有功能
            if (currentUser->type == USER_COURIER) {
                if (choice == 1) {
                    printf("\n包裹入库功能需在主菜单->包裹管理中访问\n");
                    printf("\n按Enter键继续...");
                    getchar();
                    continue;
                }
            }

            // 工作人员特有功能
            if (currentUser->type == USER_STAFF) {
                if (choice == 1) {
                    printf("\n发送通知功能需在主菜单->通知管理中访问\n");
                    printf("\n按Enter键继续...");
                    getchar();
                    continue;
                }
                else if (choice == 2) {
                    printf("\n货架管理功能需在主菜单中访问\n");
                    printf("\n按Enter键继续...");
                    getchar();
                    continue;
                }
                else if (choice == 3) {
                    printf("\n用户查询功能需在主菜单->用户管理中访问\n");
                    printf("\n按Enter键继续...");
                    getchar();
                    continue;
                }
            }

            // 处理普通用户共享的功能
            running = handleRegularUserFunctions(data, currentUser, choice);
        }
    }
}

// 处理用户登录流程
User* handleUserLogin(SystemData* data) {
    char phone[MAX_PHONE_LEN];
    char password[MAX_PASSWORD_LEN];

    printf("\n=== 用户登录 ===\n");
    printf("手机号: ");
    scanf("%s", phone);
    clearInputBuffer();

    printf("密码: ");
    scanf("%s", password);
    clearInputBuffer();

    User* currentUser = loginUser(data, phone, password);

    if (currentUser != NULL) {
        printf("\n登录成功！欢迎, %s (%s)\n",
            currentUser->username, getUserTypeString(currentUser->type));
    }
    else {
        printf("\n登录失败，手机号或密码错误！\n");
    }

    printf("\n按Enter键继续...");
    getchar();

    return currentUser;
}

// 处理用户注册流程
ErrorCode handleUserRegistration(SystemData* data) {
    char username[MAX_USERNAME_LEN];
    char password[MAX_PASSWORD_LEN];
    char phone[MAX_PHONE_LEN];
    char address[MAX_ADDRESS_LEN];
    int typeChoice;
    UserType type;
    system("cls");
    printf("\n=====================================\n");
    printf("用户注册\n");
    printf("=====================================\n");

    printf("用户名: ");
    scanf("%s", username);
    clearInputBuffer();

    printf("密码: ");
    scanf("%s", password);
    clearInputBuffer();

    printf("手机号: ");
    scanf("%s", phone);
    clearInputBuffer();

    printf("地址: ");
    scanf("%s", address);
    clearInputBuffer();

    printf("用户类型:\n");
    printf("1. 普通用户\n");
    printf("2. 快递员\n");
    printf("请选择 (默认为普通用户): ");
    scanf("%d", &typeChoice);
    clearInputBuffer();

    if (typeChoice == 1) {
        type = USER_STUDENT;
    }
    if (typeChoice == 2) {
        type = USER_COURIER;
    }
    else {
        type = USER_STUDENT;
    }

    ErrorCode result = registerUser(data, username, password, phone, address, type, NULL);

    if (result == OK) {
        result = saveUsersToFile(data, USERS_FILE);
    }
    if (result == OK) {
        printf("\n注册成功！请使用手机号和密码登录。\n");
    }
    else {
        printf("\n注册失败，错误码: %d\n", result);
        switch (result) {
        case ERR_INVALID_PARAM:
            printf("输入参数无效！\n");
            break;
        case ERR_DUPLICATE:
            printf("该手机号已注册！\n");
            break;
        default:
            printf("未知错误！\n");
            break;
        }
    }

    printf("\n按Enter键继续...");
    getchar();

    return result;
}